package _interview150;

import java.util.Arrays;

/**
 * 322. 零钱兑换
 */
public class No322 {
    private int[] coins;
    private int[][] cache;

    public int coinChange(int[] coins, int amount) {
        Arrays.sort(coins);
        this.coins = coins;
        int n = coins.length;
        cache = new int[n][amount + 1];
        for (int i = 0; i < n; i++) {
            cache[i][0] = 0;
            for (int j = 1; j < amount + 1; j++) {
                cache[i][j] = -1;
            }
        }
        int ans = dfs(n - 1, amount);
        return ans < Integer.MAX_VALUE / 2 ? ans : -1;
    }

    private int dfs(int i, int c) {
        if (c < 0 || i < 0) return Integer.MAX_VALUE / 2;
        else if (cache[i][c] != -1) return cache[i][c];
        else if (coins[i] > c) return cache[i][c] = dfs(i - 1, c);
        else return cache[i][c] = Math.min(dfs(i - 1, c), dfs(i, c - coins[i]) + 1);
    }
}